package com.gem.talkbase.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.gem.talkbase.R;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.util.LoginService;
import com.gem.talkbase.util.Split_String;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class LocationPeople extends Activity {


	private ListView listview;
	private SimpleAdapter listItemAdapter;
	private String fujinpeople;
	String requestPath=Client.Firend_info_URL;
	private Handler handler = new Handler(){

		@Override

		public void handleMessage(Message msg) {

			switch(msg.what){

			case 1:   

				Bundle data1 = msg.getData();  
				byte[] by = data1.getByteArray("by");  
				String str = data1.getString("name");
				//System.out.println("++++++case===case===case++++++++++++"+str);
				Bitmap	bitmap =  Bytes2Bimap(by);
				File f;
				if(str.length()>4){
					if(str.substring(str.length()-4, str.length()).equals(".png")){
						f = new File("/mnt/sdcard/"+str);//把图片保存到本地
					}else{
						f = new File("/mnt/sdcard/"+str+".png");//把图片保存到本地
					}
				}else{
					f = new File("/mnt/sdcard/"+str+".png");//把图片保存到本地
				}
				try {
					f.createNewFile();

					FileOutputStream fOut = null;

					fOut = new FileOutputStream(f);

					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);

					fOut.flush();

					fOut.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				break ;

			case 2:   //搜索附近的人

				Bundle data = msg.getData();  
				String result = data.getString("result");
				String zan = data.getString("zan");
				String[] tt = result.split( Split_String.split_s1);
				
				if(zan!=null&&zan!=""){
					
				}else{
					zan="0";
				}

				if(tt.length >1){
					String username = tt[0];
					String nicheng = tt[1];
					String sex = tt[2];
					//处理UI更新等操作  
					Intent intent = new Intent(LocationPeople.this,Fragment_find_AddFriend.class);
					intent.putExtra("username",username);
					intent.putExtra("nicheng",nicheng);
					intent.putExtra("sex",sex);
					intent.putExtra("zan",zan);
					LocationPeople.this.startActivity(intent);
				}else{
					Toast.makeText(LocationPeople.this, "没有搜到好友哦！亲", 0).show();
				}
				break;
			case 3:
				Toast.makeText(LocationPeople.this, "获取好友失败", 0).show();
				break;
			}
		}
	};
	private ArrayList< HashMap<String, Object>> list = new ArrayList< HashMap<String, Object>>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fragment_find_location);

		/*---------------------------------附近的人显示界面---------------------------------------------------------*/
		listview = (ListView) findViewById(R.id.listview);
		Bundle extras = getIntent().getExtras();
		fujinpeople = extras.getString("fujinpeople");//获得从主页面传来的昵称

       // getPicture1("location_nv.png");
        //getPicture1("location_nan.png");

		final String  count = fujinpeople;
		System.out.println(".........count......."+count);
		if(count!=null&&count!=""&&count.length()>5){
			String[] str = count.split(Split_String.split_s1);
			for(int i=0;i<str.length;i++){
				HashMap<String, Object> map = new HashMap<String, Object>();
				String[] str1 = str[i].split(Split_String.split_s2);

               
				
				if(str1[4].length()>4){
					if(str1[4].substring(str1[4].length()-4, str1[4].length()).equals(".png")){

					}else{
						str1[4] = str1[4]+".png";
					}
				}else{
					str1[4] = str1[4]+".png";
				}

				//获取头像的类
				getPicture(str1[4]);

                int xingbie=0;
				if(str1[5].equals("男")){
					xingbie = R.drawable.location_nan;
				}else{
					xingbie = R.drawable.location_nv;
				}
				
				map.put("ItemImage", Environment.getExternalStorageDirectory().getPath()+"/"+str1[4]);//图像资源的ID  str1[0]为唯一的id
				map.put("user_nicheng", str1[1]);//昵称
				map.put("juli", "与你相距"+str1[2]+"米");//距离
				//map.put("zan", str1[3]);
				map.put("image_xingbie", xingbie);
				System.out.println(str1[1]+"............"+str1[2]);
				list.add( map);
			}
			listItemAdapter = new SimpleAdapter(LocationPeople.this,
					list, //数据资源
					R.layout.fragment_find_location_items,//ListItem的XML实现 
					new String[]{"ItemImage","user_nicheng","juli","image_xingbie"}, //动态数组与ImageItem对应的子项
					new int[]{R.id.image, R.id.text1,R.id.text2,R.id.xingbie}); //ImageItem的XML文件里面的一个ImageView,两个TextView ID  
			listview.setAdapter(listItemAdapter);
		}else{

			Toast.makeText(LocationPeople.this, "附近没有好友哦！亲", 1).show();
		}



		/*----------------------------------------为每一个选项添加监听事件，去聊天-----------------------------------------------*/

		//添加点击  
		listview.setOnItemClickListener(new OnItemClickListener() {  

			@Override  
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
					long arg3) {  
				System.out.println("点击第"+arg2+"个项目");  
				String[] str = count.split(Split_String.split_s1);
				final String[] str1 = str[arg2].split(Split_String.split_s2);
				final String str2 = str1[3];
				new Thread(){
					public void run(){
						final String result = LoginService.serchByGet(str1[0]);
						if(result != null){
							System.out.println("到了runnable 中。。。。");
							Message msg = new Message() ;
							Bundle data = new Bundle();  
							data.putString("result", result);//result是标签,handleMessage中使用 
							data.putString("zan", str2);
							msg.setData(data); 
							msg.what = 2 ;	  
							LocationPeople.this.handler.sendMessage(msg);
						}else{
							//当没有好友时，则获取好友失败
							Message msg = new Message() ;
							msg.what = 3 ;	  
							LocationPeople.this.handler.sendMessage(msg);
						}  
					};
				}.start();  

			}  
		});  

	}




	/*------------------------------------从服务器获取头像--------------------------------------*/		
	public void getPicture(final String str){
		if(fileIsExists("/mnt/sdcard/"+str)){

		}else{
			new Thread(new Runnable() {

				@Override
				public void run() {
					Bitmap	bitmap = getImage(Client.URL_getpic+str);
					byte[] by = Bitmap2Bytes(bitmap);
					if(by!=null){
						Message msg = new Message() ;
						//这三句可以传递数据  
						Bundle data = new Bundle();  
						data.putByteArray("by", by);//COUNT是标签,handleMessage中使用  
						data.putString("name", str);//把用户的名字传过去。。。
						msg.setData(data);  
						msg.what = 1 ;

						LocationPeople.this.handler.sendMessage(msg);
					}

				}


			}).start();
		}
	}

	
	
	
/*	------------------------------------从服务器获取头像--------------------------------------		
	public void getPicture1(final String str){
		if(fileIsExists("/mnt/sdcard/"+str)){

		}else{
			new Thread(new Runnable() {

				@Override
				public void run() {
					Bitmap	bitmap = getImage(Client.URL_getpic+str);
					byte[] by = Bitmap2Bytes(bitmap);
					if(by!=null){
						Message msg = new Message() ;
						//这三句可以传递数据  
						Bundle data = new Bundle();  
						data.putByteArray("by", by);//COUNT是标签,handleMessage中使用  
						data.putString("name", str);//把用户的名字传过去。。。
						msg.setData(data);  
						msg.what = 1 ;

						LocationPeople.this.handler.sendMessage(msg);
					}

				}


			}).start();
		}
	}*/



	/*------------------------------------byte[]转化为Bitmap--------------------------------------*/	

	public Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}


	/*------------------------------------Bitmap转化为byte[]--------------------------------------*/	
	public byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/*------------------------------------输入指定的路径，然后得到图片--------------------------------------*/	
	public  Bitmap getImage(String urlpath)   {   
		URL url;
		Bitmap bitmap = null;   
		try {
			url = new URL(urlpath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
			conn.setRequestMethod("GET");   
			conn.setConnectTimeout(5 * 1000);   
			if (conn.getResponseCode() == 200) {   
				InputStream inputStream = conn.getInputStream();   
				bitmap = BitmapFactory.decodeStream(inputStream);
				System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++");

			}else{
				Resources res= getResources();
				System.out.println("==================================================");
				bitmap=BitmapFactory.decodeResource(res, R.drawable.head_no); 
			}   
			return bitmap; 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("---------------------------------------------------------");
			Resources res= getResources();

			bitmap=BitmapFactory.decodeResource(res, R.drawable.head_no); 
			return bitmap;   
		}   
	}  




	/*-------------------------------------------去空格，换行等--------------------------------------------------*/

	public static String replaceBlank(String str) {  
		String dest = "";  
		if (str!=null) {  
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");  
			Matcher m = p.matcher(str);  
			dest = m.replaceAll("");  
		}  
		return dest;  
	}  




	/*-------------------------------判断本地是否有某张图片-----------------------------------*/
	public boolean fileIsExists(String str){
		try{
			File f=new File(str);
			if(!f.exists()){
				return false;
			}

		}catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		return true;
	}


}
